package com.leyou.sh.auth.service.impl;

import com.leyou.sh.auth.dto.JwtConstants;
import com.leyou.sh.auth.dto.Payload;
import com.leyou.sh.auth.dto.UserDetail;
import com.leyou.sh.auth.service.UserAuthService;
import com.leyou.sh.auth.utils.JwtUtils;
import com.leyou.sh.common.exception.LyException;
import com.leyou.sh.common.utils.CookieUtils;
import com.leyou.sh.user.client.UserClient;
import com.leyou.sh.user.dto.UserDTO;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.leyou.sh.auth.dto.JwtConstants.COOKIE_NAME;
import static com.leyou.sh.auth.dto.JwtConstants.KEY_PREFIX;

/**
 * @author balisong_fcs
 * @date 2021/1/11 22:12
 * @desc
 */
@Service
@Slf4j
public class UserAuthServiceImpl implements UserAuthService {
    @Autowired
    private UserClient userClient;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void login(String username, String password, HttpServletResponse response) {

        UserDTO userDTO = null;
        try {
            userDTO = this.userClient.queryUserByNameAndPassWord(username, password);
        } catch (FeignException e) {
            throw new LyException(e.status(), e.getMessage());
        }

        if (null == userDTO) {
            throw new LyException(400, "无此用户,请先注册");
        }
        UserDetail userDetail = new UserDetail();
        BeanUtils.copyProperties(userDTO, userDetail);
        //token
        String token = jwtUtils.createJwt(userDetail);
        //cookie name+value
        Cookie cookie = new Cookie(COOKIE_NAME, token);
        //设置域,访问此域,则携带此cookie,子域名同样有效
        cookie.setDomain("leyou.com");
        //设置path,即适配域+"/"后的所有路径
        cookie.setPath("/");
        //默认为-1,即长期有效
        //cookie.setMaxAge(-1);
        //设置cookie拒绝脚本访问
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        String token = CookieUtils.getCookieValue(request, COOKIE_NAME);
        try {
            Payload payload = jwtUtils.parseJwt(token);
            String key = KEY_PREFIX + payload.getUserDetail().getId();
            this.redisTemplate.delete(key);
            log.info("用户推出成功");
        } catch (Exception e) {

        }
        //重新生成cookie
        Cookie cookie = new Cookie(COOKIE_NAME, "");
        cookie.setPath("/");
        cookie.setDomain("leyou.com");
        cookie.setHttpOnly(true);
        //cookie设置为0立即删除,设置-1或默认,为永不失效
        cookie.setMaxAge(0);
    }
}
